package hu.mapro.rollerx.core;

import com.badlogic.gdx.graphics.g2d.PolygonRegion;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.operation.buffer.BufferBuilder;
import com.vividsolutions.jts.operation.buffer.BufferParameters;

public class Grounds {

	public static Vector2[][] createCave(Geometry lineString, BufferParameters bufferParameters, float caveHeight) {
		
		BufferBuilder bufferBuilder = new BufferBuilder(bufferParameters);
		Polygon buffer = (Polygon) bufferBuilder.buffer(lineString, caveHeight);
		
		Vector2[][] vecs = new Vector2[buffer.getNumInteriorRing()+1][];
		
		vecs[0] = Grounds.toVector2(buffer.getExteriorRing());
		
		for (int i=0;i<buffer.getNumInteriorRing();i++) {
			vecs[i+1] = Grounds.toVector2(buffer.getInteriorRingN(i));
		}
		
		return vecs;
	}

	public static Vector2[] toVector2(LineString lineString) {
		Coordinate[] coordinates = lineString.getCoordinates();
		Vector2[] result = new Vector2[coordinates.length-1];
		
		for (int i=0;i<coordinates.length-1;i++) {
			result[i] = new Vector2((float)coordinates[i].x, (float)coordinates[i].y);
		}
	
		return result;
	}

	public static Vector2[][] createCave(Coordinate[] coordinates, BufferParameters bufferParameters, float caveHeight) {
		GeometryFactory geometryFactory = new GeometryFactory();
		LineString lineString = geometryFactory.createLineString(coordinates);
		return createCave(lineString, bufferParameters, caveHeight);
	}

	public static void textureMap(PolygonRegion region, float scale) {
		float[] textureCoords = region.getTextureCoords();
		TextureRegion textureRegion = region.getRegion();
		float u = textureRegion.getU(), v = textureRegion.getV();
		float uvWidth = textureRegion.getU2() - u;
		float uvHeight = textureRegion.getV2() - v;
		float width = textureRegion.getRegionWidth() * scale;
		float height = textureRegion.getRegionHeight() * scale;
		float[] vertices = region.getVertices();
		for (int i = 0, n = vertices.length; i < n; i++) {
			textureCoords[i] = u + uvWidth * (vertices[i] / width);
			i++;
			textureCoords[i] = v + uvHeight * (1 - (vertices[i] / height));
		}
		
	}

	
}
